package com.srcpit.orc.docs;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import com.google.gdata.data.MediaContent;
import com.google.gdata.data.docs.DocumentListEntry;
import com.google.gdata.data.docs.DocumentListFeed;
import com.google.gdata.data.media.MediaSource;
import com.google.gdata.util.AuthenticationException;
import com.google.gdata.util.ServiceException;

public class Main {

	private DocumentList documentList;
	private static final String APPLICATION_NAME = "JavaGDataClientSampleAppV3.0";

	public Main() {
		try {
			System.out.println("Login....\n");
			documentList = new DocumentList(APPLICATION_NAME);
			login();
			upload();
		} catch (DocumentListException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void login() {
		try {
			documentList.login("srcptit", "mainhatrithuc");
			System.out.println("Login success!\n");
		} catch (AuthenticationException | DocumentListException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void printDocuments(DocumentListFeed feed) {
		
	}

	private void upload() {
		try {
			System.out.println("Uploading... \n");
			DocumentListEntry doc = documentList.uploadFile("D:/a.png", "test");
			System.out.println("Upload success!\n");
			String id = doc.getDocId();
			String link = "https://docs.google.com/feeds/download/documents/export/Export?id="+id+"&exportFormat=txt";
			System.out.println(link);
			MediaContent mc = (MediaContent) doc.getContent();
			
			mc.setUri(link);
		    MediaSource ms = documentList.getMedia(mc);
		    if(ms != null) {
		    	InputStream is = ms.getInputStream(); 
		    	BufferedReader br = null;
		    	StringBuilder sb = new StringBuilder();
		    	String line;
		    	br = new BufferedReader(new InputStreamReader(is));
				while ((line = br.readLine()) != null) {
					sb.append(line);
				}
				System.out.println("Content: " + sb.toString());
		    } else {
		    	System.out.println("No content");
		    }

		} catch (IOException | ServiceException | DocumentListException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static void main(String agrs[]) {
		new Main();
	}
}
